﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Xml.Linq;
using System.Threading;
using System.Globalization;
using Nivdal.AuxCode;

namespace Nivdal
{
    public partial class league : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Title = Resources.Resource.Default_PageTitle + ", " + Resources.Resource.league_PageTitle;
            //if (!HttpContext.Current.User.Identity.IsAuthenticated)
            //    Response.Redirect("Default.aspx");
            
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            
            this.Title = GND.ReturnAppTitle();
            //if (ou.TeamId == "Null")
            //    Response.Redirect("~/GeneralMessage.aspx?MessageString=M74ggdizz5wfeh");

            string LeagueId = null;
            if (Request.QueryString["LeagueId"] != null)
                LeagueId = Request.QueryString["LeagueId"].ToString();
            else
                Response.Redirect("GeneralMessage.aspx?MessageString=l4OF1EOTHJA");
   
            if (!IsPostBack)
            {
                CountryIdHiddenField.Value = GND.ReadNivdalIntData("LeagueId", "Nivdal_GetCountryByLeague", LeagueId);
                this.SqlDataSource1.SelectParameters.Add("LeagueId", LeagueId);
                this.SqlDataSource1.SelectParameters.Add("Language", ou.Language);
                this.SqlDataSource2.SelectParameters.Add("LeagueId", LeagueId);
                this.SqlDataSource5.SelectParameters.Add("LeagueId", LeagueId);
                this.SqlDataSource5.SelectParameters.Add("Language", ou.Language);
                this.SqlDataSource6.SelectParameters.Add("LeagueId", LeagueId);
                this.SqlDataSource6.SelectParameters.Add("Language", ou.Language);
                this.TopScorersDataSourse.SelectParameters.Add("LeagueId", LeagueId);
                this.LeagueLevelsDataSource.SelectParameters.Add("CountryId", CountryIdHiddenField.Value);
                this.LeagueLevelsDataSource.SelectParameters.Add("Language", ou.Language);
            }
            if (string.IsNullOrEmpty(CountryIdHiddenField.Value.ToString()))
                Response.Redirect("~/Default.aspx");
            this.FixturesPageLinkButton.NavigateUrl = "~/LeagueFixtures.aspx?LeagueId=" + LeagueId;
            this.OldLeaguLinkButton.NavigateUrl = "~/OldLeagueTables.aspx?LeagueId=" + LeagueId;

            if (GND.IsUserPremium())
            {
                this.BookmarkButton.Visible = true;
            }

            // reading top data
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            SqlCommand cmd = new SqlCommand("Nivdal_ShowLeagueDetails", conn);
            SqlDataReader reader;
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add("@LeagueId", SqlDbType.Decimal, 12);
            cmd.Parameters["@LeagueId"].Value = LeagueId;
            cmd.Parameters["@LeagueId"].Direction = ParameterDirection.Input;

            cmd.Parameters.Add("@Language", SqlDbType.Decimal, 3);
            cmd.Parameters["@Language"].Value = ou.Language;
            cmd.Parameters["@Language"].Direction = ParameterDirection.Input;

            try
            {
                conn.Open();
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    this.LeagueNameLabel.Text = reader.GetString(0);
                    this.LeagueLevelLabel.Text = reader.GetString(1);
                    this.CountryFlagImage.PostBackUrl = "Country.aspx?Id=" + reader.GetDecimal(2).ToString();
                    this.CountryFlagImage.ToolTip = reader.GetString(3);
                    this.CountryFlagImage.ImageUrl = "~/Images/Flags/" + reader.GetString(4);
                    this.ForumImageButton.PostBackUrl = "~/ForumDetails.aspx?Id=" + reader.GetDecimal(6).ToString();
                }
            }
            catch (Exception)
            {
                Response.Write("connection Failure");
            }
            finally
            {
                conn.Close();
            }
            BonusPromotionHyperlink.NavigateUrl = "~/BonusPromotions.aspx?LeagueId=" + LeagueId;
            bool MatchesPlayed = GND.ReadNivdalBoolData("LeagueId", "Nivdal_AreMatchesBeingPlayedInLeague", LeagueId);
            this.ScorersPanel.Visible = !MatchesPlayed;
            if (MatchesPlayed)
            {
                this.NextRoundLabel.Text = Resources.Resource.league_OngoingMatchesTitleLabel;
            }

            string NextRoundDate = GND.ReadNivdalStringData("LeagueId", "Nivdal_GetNextLeagueRoundDate", LeagueId);

            if (NextRoundDate == "not available")
                NextRoundMatchesDateLabel.Visible = false;
            else
                NextRoundMatchesDateLabel.Text = "(" + NextRoundDate + ")";
            LeagueIdHiddenFirld.Value = LeagueId;
            AddAllRoundToLiveButton.Visible = GND.ReadNivdalBoolData("LeagueId", "Nivdal_AddNextLeagueRoundToLiveVisible", LeagueId);
        }

        protected bool IsPremium()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            return ou.IsPremium;
        }

        protected System.Drawing.Color GDColumnColor(Object RowNum)
        {
            string LeagueId = null;
            LeagueId = LeagueIdHiddenFirld.Value;
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            if (!GND.ReadNivdalBoolData("@LeagueId", "Nivdal_IsLastLeagueLevel", LeagueId))
            {

                if (RowNum.ToString() == "1")
                    return System.Drawing.Color.Green;
                if (RowNum.ToString() == "2")
                    return System.Drawing.Color.LightGray;
                if (RowNum.ToString() == "3")
                    return System.Drawing.Color.White;
                if (RowNum.ToString() == "4")
                    return System.Drawing.Color.LightGray;
                if (RowNum.ToString() == "5")
                    return System.Drawing.Color.White;
                if (RowNum.ToString() == "5")
                    return System.Drawing.Color.White;
                if (RowNum.ToString() == "6")
                    return System.Drawing.Color.LightGray;
                if (RowNum.ToString() == "7")
                    return System.Drawing.Color.White;
                else if (RowNum.ToString() == "8")
                    return System.Drawing.Color.Red;
                else if (RowNum.ToString() == "9")
                    return System.Drawing.Color.Red;
                else if (RowNum.ToString() == "10")
                    return System.Drawing.Color.Red;
                else
                    return System.Drawing.Color.Empty;
            }
            else
            {
                return System.Drawing.Color.Empty;
            }
        }

        protected void BookmarkButton_Click(object sender, EventArgs e)
        {
            String LeagueId = LeagueIdHiddenFirld.Value;
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];

            string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            System.Data.IDbConnection dbConnection = new System.Data.SqlClient.SqlConnection(conn);
            System.Data.IDbCommand dbCommand = new System.Data.SqlClient.SqlCommand();
            dbCommand.CommandText = "Nivdal_BookmarkLeague";
            dbCommand.CommandType = CommandType.StoredProcedure;
            dbCommand.Connection = dbConnection;

            SqlParameter dbParam_UserId = new SqlParameter();
            dbParam_UserId.ParameterName = "@UserId";
            dbParam_UserId.Value = ou.UserId;
            dbParam_UserId.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_UserId);

            SqlParameter dbParam_BookmarkedPlayer = new SqlParameter();
            dbParam_BookmarkedPlayer.ParameterName = "@BookmarkedLeague";
            dbParam_BookmarkedPlayer.Value = LeagueId;
            dbParam_BookmarkedPlayer.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_BookmarkedPlayer);

            SqlParameter dbParam_Answer = new SqlParameter();
            dbParam_Answer.ParameterName = "@Answer";
            dbParam_Answer.Value = "";
            dbParam_Answer.DbType = DbType.String;
            dbParam_Answer.Direction = ParameterDirection.Output;
            dbParam_Answer.Size = 64;
            dbCommand.Parameters.Add(dbParam_Answer);

            try
            {

                dbConnection.Open();
                dbCommand.ExecuteScalar();
                Response.Redirect("Bookmarks.aspx?ConfirmNote=" + dbParam_Answer.Value.ToString());
            }
            catch (Exception SQLDBException)
            {
                this.ErrorLabel.Text = Convert.ToString(SQLDBException);
            }

            finally
            {
                dbConnection.Close();
            }

        }

        protected override void InitializeCulture()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(ou.UICulture);
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ou.Culture);
        }

        protected void NextRoundMatchesCommand(object sender, GridViewCommandEventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];

            if (e.CommandName == "AddToLive")
            {
                GND.ExecNivdalSQL("MatchId", "UserId", "Nivdal_LiveAddMatchToLive", e.CommandArgument, ou.UserId);
                Response.Redirect("Live.aspx");
            }
            else if (e.CommandName == "Bookmark")
            {
                string Answer = GND.ReadNivdalStringData("BookmarkedMatch", "UserId", "Nivdal_BookmarkMatchSelect", e.CommandArgument, ou.UserId);
                Response.Redirect("Bookmarks.aspx?ConfirmNote=" + Answer);
            }

        }

        protected void AddAllRoundToLive(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            GND.ExecNivdalSQL("UserId", "LeagueId", "Nivdal_AddNextLeagueRoundToLive", ou.UserId, LeagueIdHiddenFirld.Value);
            Response.Redirect("Live.aspx");
        }

        protected void GoToLeague(object sender, EventArgs e)
        {
            string LeagueId = NumberDropDownList.SelectedValue;
            if (LeagueId != "0")
            {
                Response.Redirect("league.aspx?LeagueId=" + LeagueId);
            }
        }

        protected void LevelSelected(object sender, EventArgs e)
        {
            string LevelId = LevelsDDL.SelectedValue;
            string Country = CountryIdHiddenField.Value;
            NumberDropDownList.Visible = true;
            NumberDropDownList.Items.Clear();
            NumberDropDownList.Items.Add(new ListItem(Resources.Resource.league_SelectNumber, "0"));
            string LeagueId, LeagueNumber;

            using (SqlConnection myConnection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
            {
                SqlCommand cmd = new SqlCommand("Nivdal_GetListOfLeaguesInLevelInCountry", myConnection);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.Parameters.Add("CountryId", System.Data.SqlDbType.Decimal, 3);
                cmd.Parameters["CountryId"].Value = Country;

                cmd.Parameters.Add("LeagueLevel", System.Data.SqlDbType.Decimal, 3);
                cmd.Parameters["LeagueLevel"].Value = LevelId;

                SqlDataReader reader;

                try
                {
                    myConnection.Open();
                    reader = cmd.ExecuteReader();

                    while (reader.Read())
                    {
                        LeagueId = reader.GetDecimal(0).ToString();
                        LeagueNumber = reader.GetDecimal(1).ToString();
                        NumberDropDownList.Items.Add(new ListItem(LeagueNumber, LeagueId));
                    }
                }
                catch { }
                finally { myConnection.Close(); }

            }


        }

        public bool IsAllowedLive(Object CanAddToLive)
        {
            GlobalFunctions GF = new GlobalFunctions();
            return GF.IsAllowedLive(CanAddToLive);
        }
    }
}